<template>
  <div>
    <a-row :gutter="24">
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="总内存" :total="hardWareInfo.memory_total">
          <a-tooltip title="实时显示内存使用情况如下" slot="action">
            <a-icon type="info-circle-o" />
          </a-tooltip>
          <div>
            <trend flag="up" style="margin-right: 16px;">
              <span slot="term">内存使用率</span>
              {{ hardWareInfo.memory_use_rate }}
            </trend>
            <mini-progress color="rgb(19, 194, 194)" :target="100" :percentage="memoryUse" height="8px" />
          </div>
          <template slot="footer">

            <trend flag="down" style="margin-right: 16px;">
              <span slot="term">使用</span>
              {{ hardWareInfo.memory_use_total | NumberFormat }}
            </trend>

            <trend flag="up">
              <span slot="term">剩余</span>
              {{ hardWareInfo.memory_surplus_total | NumberFormat }}
            </trend>

          </template>
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="CPU 核心数" :total="(hardWareInfo.cpu_core_total )+'核心'">
          <a-tooltip title="CPU 使用监控" slot="action">
            <a-icon type="info-circle-o" />
          </a-tooltip>
          <div>
            <mini-area :val="hardWareInfo.cpu_use"/>
          </div>
          <template slot="footer">
            <trend flag="down" style="margin-right: 16px;">
              <span slot="term">系统占用</span>
              {{ hardWareInfo.cpu_sys_use | NumberFormat }}
            </trend>
            <trend flag="up">
              <span slot="term">用户占用</span>
              {{ hardWareInfo.cpu_usr_use | NumberFormat }}
            </trend>
          </template>
        </chart-card>
      </a-col>

      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="JVM总内存" :total="hardWareInfo.jvm_total">
          <a-tooltip title="实时显示JVM内存使用情况如下" slot="action">
            <a-icon type="info-circle-o" />
          </a-tooltip>
          <div>
            <trend flag="up" style="margin-right: 16px;">
              <span slot="term">JVM使用率</span>
              {{ hardWareInfo.jvm_use_rate }}
            </trend>
            <mini-progress color="rgb(19, 194, 194)" :target="100" :percentage="jvmUse" height="8px" />
          </div>
          <template slot="footer">

            <trend flag="down" style="margin-right: 16px;">
              <span slot="term">使用</span>
              {{ hardWareInfo.jvm_use_total | NumberFormat }}
            </trend>

            <trend flag="up">
              <span slot="term">剩余</span>
              {{ hardWareInfo.jvm_surplus_total | NumberFormat }}
            </trend>

          </template>
        </chart-card>
      </a-col>

      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="运行环境" :total="hardWareInfo.os_name">
          <a-tooltip title="系统信息概览" slot="action">
            <a-icon type="info-circle-o" />
          </a-tooltip>
          <div>
            <trend flag="up1" style="margin-right: 16px;">
              <span slot="term">系统架构</span>
              {{ hardWareInfo.os_arch }}
            </trend>

            <trend flag="up1" style="margin-right: 16px;">
              <span slot="term">JDK版本</span>
              {{ hardWareInfo.java_version }}
            </trend>

          </div>
          <template slot="footer">
            <trend flag="down1" style="margin-right: 16px;">
              <span slot="term">JDK:</span>
              {{ hardWareInfo.java_home }}
            </trend>
          </template>
        </chart-card>
      </a-col>
    </a-row>

    <a-card :loading="loading" :bordered="false" :body-style="{padding: '0'}">
      <div class="salesCard">
        <a-tabs default-active-key="1" size="large" :tab-bar-style="{marginBottom: '24px', paddingLeft: '16px'}">
          <!--          <div class="extra-wrapper" slot="tabBarExtraContent">
            <div class="extra-item">
              <a>今日</a>
              <a>本周</a>
              <a>本月</a>
              <a>本年</a>
            </div>
            <a-range-picker :style="{width: '256px'}" />
          </div> -->
          <a-tab-pane loading="true" tab="发布文章量" key="1">
            <a-row>
              <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
                <bar :data="barData" title="发帖量排行" />
              </a-col>
              <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <rank-list title="栏目文章数量排行" :list="rankList"/>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-card>

    <div class="antd-pro-pages-dashboard-analysis-twoColLayout" :class="!isMobile && 'desktop'">
      <a-row :gutter="24" type="flex" :style="{ marginTop: '24px' }">
        <a-col :xl="12" :lg="24" :md="24" :sm="24" :xs="24">
          <a-card :loading="loading" :bordered="false" title="我的操作记录" :style="{ height: '100%' }">
            <div class="ant-table-wrapper">
              <s-table
                ref="table"
                size="small"
                bordered
                rowKey="id"
                :columns="columns"
                :data="loadData">
                <span
                  slot="method"
                  slot-scope="text">
                  <span v-html="$substr(text,10)"></span>
                </span>
              </s-table>
            </div>
          </a-card>
        </a-col>
        <a-col :xl="12" :lg="24" :md="24" :sm="24" :xs="24">
          <a-card class="antd-pro-pages-dashboard-analysis-salesCard" :loading="loading" :bordered="false" :title="'硬盘占比( 总容量:'+hardWareInfo.hardDrive_total+')'" :style="{ marginTop: '24px', minHeight: '500px' }">
            <div slot="extra" style="height: inherit;">
              <!-- style="bottom: 12px;display: inline-block;" -->
            </div>
            <div>
              <!-- style="width: calc(100% - 240px);" -->
              <div>
                <v-chart :force-fit="true" :height="405" :data="pieData" :scale="pieScale">
                  <v-tooltip :showTitle="false" dataKey="item*percent" />
                  <v-axis />
                  <!-- position="right" :offsetX="-140" -->
                  <v-legend dataKey="item"/>
                  <v-pie position="percent" color="item" :vStyle="pieStyle" />
                  <v-coord type="theta" :radius="0.75" :innerRadius="0.6" />
                </v-chart>
              </div>

            </div>
          </a-card>
        </a-col>
      </a-row>
      <a-row :gutter="24"  :style="{ marginTop: '24px',textAlign: 'center' }">
        <my-ads ref="myAds"></my-ads>
      </a-row>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import storage from 'store'
import { MONIT_PARAMS } from '@/store/mutation-types'
import { analysisMonthTop } from '@/api/site/content'
import MyAds from '@/components/Other/MyAds'
import {
  pageForMoint
} from '@/api/system/log'
import {
  ChartCard,
  MiniArea,
  MiniBar,
  MiniProgress,
  RankList,
  Bar,
  Trend,
  NumberInfo,
  MiniSmoothArea,
  STable
} from '@/components'
import { baseMixin } from '@/store/app-mixin'


const DataSet = require('@antv/data-set')

const pieScale = [{
  dataKey: 'percent',
  min: 0,
  formatter: '.0%'
}]

export default {
  name: 'Analysis',
  mixins: [baseMixin],
  components: {
    ChartCard,
    MiniArea,
    MiniBar,
    MiniProgress,
    RankList,
    Bar,
    Trend,
    NumberInfo,
    MiniSmoothArea,
    STable,
    MyAds
  },
  data () {
    return {
      loading: true,
      rankList: [],
      interval: null,
      barData: [],
      queryParam: {
        dto: {}
      },
      pieScale,
      pieData: [],
      pieStyle: {
        stroke: '#fff',
        lineWidth: 1
      },
      hardWareInfo: {
        threads: [],
        hardDrive_total: '载入中'
      },
      cpuUse: 0,
      jvmUse: 0,
      memoryUse: 0,
      columns: [
           {
             title: '模块名称',
             dataIndex: 'module'
           },
           {
             title: '用户方法',
             dataIndex: 'operation'
           },
           {
             title: '响应时间',
             dataIndex: 'time',
             customRender: (text) => {
               if (text < 1000) {
                 return text + '  ms'
               } else if (text >= 1000) {
                 return (text / 1000) + '  s'
               } else {
                 return text + '  ms'
               }
             }
           },
           {
             title: '请求方法',
             dataIndex: 'method',
             scopedSlots: {
               customRender: 'method'
             }
           },
           {
             title: 'IP地址',
             dataIndex: 'ip'
           },
           {
             title: '创建时间',
             dataIndex: 'gmtCreate',
             sorter: true,
             needTotal: false,
             customRender: (text) => {
               if (text) { return moment(text).format('YYYY-MM-DD HH:mm:ss') }
             }
           }
           ],
      loadData: parameter => {
        return pageForMoint(Object.assign(parameter, this.queryParam)).then(response => {
          return response.res
        })
      }
    }
  },
  created () {
    const _this = this
    if (!this.interval) {
      this.interval = setInterval(function () {
                 const params = storage.get(MONIT_PARAMS)
                 _this.hardWareInfo = params
                 _this.setUseRate(params)
       }, 800)
    }
    this.queryMonthTop()
    setTimeout(() => {
      this.loading = !this.loading
    }, 1000)
  },
  mounted () {
    this.showMessage()
  },
  methods: {
    setUseRate (hardWareInfo) {
      this.cpuUse = this.getUseRate(hardWareInfo.cpu_use)
      this.jvmUse = this.getUseRate(hardWareInfo.jvm_use_rate)
      this.memoryUse = this.getUseRate(hardWareInfo.memory_use_rate)
      if (this.pieData.length === 0) {
        this.setPie(hardWareInfo.hardDrive_rate_total)
      }
    },
    getUseRate (use) {
      if (use) {
        const usrRateStr = use.replace('%', '')
        return parseInt(usrRateStr)
      } else {
        return 0
      }
    },
    setPie (hardDrives) {
      const sourceData = []
      if (hardDrives.length > 0) {
        hardDrives.forEach(function (item, index) {
          const objKeys = Object.keys(item)
          if (objKeys.length > 0) {
            objKeys.forEach(function (key, index) {
              sourceData.push({
                item: key,
                count: item[key]
              })
            })
          }
        })
      }
      // console.log(sourceData)
      const dv = new DataSet.View().source(sourceData)
      dv.transform({
        type: 'percent',
        field: 'count',
        dimension: 'item',
        as: 'percent'
      })
      this.pieData = dv.rows
    },
    queryMonthTop () {
      const _this = this
      analysisMonthTop({ status: 1 }).then(response => {
        if (response.code === 0) {
          const pdatas = response.res.publishData
          const cdatas = response.res.categoryData
          pdatas.forEach(function (item, index) {
             _this.barData.push({
               x: item.name,
               y: item.count
             })
          })
          cdatas.forEach(function (item, index) {
             _this.rankList.push({
               name: item.name,
               total: item.count
             })
          })
        }
       })
    },
    showMessage () {
        this.$notification.open({
          message: '骚年，你有新的消息',
          placement: 'bottomRight',
          duration: null,
          description:
            '骚年，加个群聊吧,一起交流、一起学习、一起扯淡吧',
          btn: h => {
            return h(
              'a-button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                on: {
                  click: () => this.joinClub()
                }
              },
              '确定加入'
            )
          }
        })
    },
    joinClub () {
     window.open('https://jq.qq.com/?_wv=1027&k=5QtXTll')
    }
  }
}
</script>

<style lang="less" scoped>
  .extra-wrapper {
    line-height: 55px;
    padding-right: 24px;

    .extra-item {
      display: inline-block;
      margin-right: 24px;

      a {
        margin-left: 24px;
      }
    }
  }

  .antd-pro-pages-dashboard-analysis-twoColLayout {
    position: relative;
    display: flex;
    display: block;
    flex-flow: row wrap;
  }

  .antd-pro-pages-dashboard-analysis-salesCard {
    height: calc(100% - 24px);
    /deep/ .ant-card-head {
      position: relative;
    }
  }

  .dashboard-analysis-iconGroup {
    i {
      margin-left: 16px;
      color: rgba(0,0,0,.45);
      cursor: pointer;
      transition: color .32s;
      color: black;
    }
  }
  .analysis-salesTypeRadio {
    position: absolute;
    right: 54px;
    bottom: 12px;
  }
</style>
